package me.devsaki.hentoid.json.sources.kemono

import com.squareup.moshi.JsonClass
import me.devsaki.hentoid.activities.sources.KEMONO_DOMAIN_FILTER
import me.devsaki.hentoid.database.domains.Chapter
import me.devsaki.hentoid.enums.StatusContent
import me.devsaki.hentoid.parsers.urlsToImageFiles
import me.devsaki.hentoid.util.getRandomInt
import me.devsaki.hentoid.util.image.isSupportedImage
import java.net.URLEncoder
import java.util.concurrent.atomic.AtomicInteger

/**
 * Kemono posts generated by calling the "posts" API endpoint
 */
@JsonClass(generateAdapter = true)
data class KemonoPost(
    val id: String,
    val user: String,
    val service: String,
    val title: String,
    val published: String?,
    val tags: List<String>?,
    val file: KemonoAttachment?,
    val attachments: List<KemonoAttachment>
) {
    fun getImageUrls(
        serverMapping: Map<String?, String?>? = null
    ): List<String> {
        // Try using attachments
        var result = attachments
            .filter { isSupportedImage(it.path ?: "") }
            .distinct()
            .map {
                val server = serverMapping?.get(it.path) ?:
                "https://n${(getRandomInt(4) + 1)}.$KEMONO_DOMAIN_FILTER"
                val origin = URLEncoder.encode(it.name, "UTF-8")
                "$server/data/${it.path}?f=$origin"
            }
        // Add file as the sole attached image
        if (result.isEmpty()) {
            file?.path?.let {
                if (isSupportedImage(it))
                    result = listOf(
                        "https://img.${KEMONO_DOMAIN_FILTER}/thumbnail/data/${it}"
                            .replace("//", "/")
                    )
            }
        }
        return result
    }

    fun toChapter(
        userId: String,
        chapterOrder: AtomicInteger,
        pageOrder: AtomicInteger
    ): Chapter {
        // One result = one chapter, if it contains at least an usable picture (i.e. not exclusively MEGA links)
        val chapter = Chapter(
            chapterOrder.andIncrement,
            "https://$KEMONO_DOMAIN_FILTER/${service}/user/${userId}/post/${id}",
            title
        )
        val imageUrls = getImageUrls()
        if (imageUrls.isNotEmpty()) {
            val imageFiles = urlsToImageFiles(
                imageUrls,
                pageOrder.get(),
                StatusContent.SAVED,
                imageUrls.count(),
                chapter
            )
            pageOrder.set(imageFiles.maxOf { it.order } + 1)
            chapter.setImageFiles(imageFiles)
        }
        return chapter
    }
}